package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


@Component
public class RedisIdWorker {
    //开始时间戳
    private static final long beginSecond = 1640995200L;//咋得出来的这个数值？
    private final StringRedisTemplate stringRedisTemplate;
    @Autowired
    private  RedisTemplate redisTemplate;
    //序列号位数
    private static final int countBits=32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 生成分布式ID
     */
    public long nextId(String keyprefix){
        //1.准备时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp= nowSecond-beginSecond;
        //2.准备序列号
        DateTimeFormatter dtf= DateTimeFormatter.ofPattern("yyyy MM dd");
        String date = dtf.format(now);//格式化LocalDateTime对象用DateTimeFormatter类的format
        Long count = stringRedisTemplate.opsForValue().increment("icr" + keyprefix +":" +date);

        //3.拼接时间戳和序列号，返回
        return timestamp<<countBits| count;
    }
}
